package tcu.yuyp.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import tcu.yuyp.pojo.Invitation;
import tcu.yuyp.pojo.R;
import tcu.yuyp.service.Utils;
import tcu.yuyp.service.impl.InvitationsServiceImpl;

import java.io.IOException;

//@ServletComponentScan
@WebServlet("/travel/invitations/*")
//处理邀请函相关的请求
public class InvitationsServlet extends HttpServlet {
    InvitationsServiceImpl invitationsServiceImpl;

    //通过构造器注入的方式实现注入
    public InvitationsServlet(InvitationsServiceImpl invitationsServiceImpl) {
        this.invitationsServiceImpl = invitationsServiceImpl;
    }


    @Override
    //发布一个邀请函 或者 用户报名参加邀请函 的方法
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应的数据格式和字符编码
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        //创建需要用到的实体对象
        var r = new R();
        var mapper = new ObjectMapper();
        var session = req.getSession();
        Invitation newInvitation = null;

        //获取请求URI
        String requestURI = req.getRequestURI();

        //获取session域中的登陆用户的名字
        String loginName;
        if (session.getAttribute("loginName") == null){
            loginName = null;
        }else {
            loginName = session.getAttribute("loginName").toString();
        }


        //判断是否为发布邀请函，如果是，需要获取请求数据
        if (Utils.getNumberOfURI(requestURI).get("getNumberOfURI") == 2) {
            newInvitation = mapper.readValue(req.getReader(), Invitation.class);
        }


        //调用service层的方法进行判断是哪一个请求，并执行对应的方法
        invitationsServiceImpl.postInvitationResponse(newInvitation,requestURI,r,loginName);


        resp.getWriter().println(mapper.writeValueAsString(r));

//        super.doPost(req, resp);
    }

    @Override
    //查看邀请函的方法
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应数据的格式和字符编码
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        var mapper = new ObjectMapper();
        var r = new R();

        //获取请求参数
        String requestURI = req.getRequestURI();//获取URI

        //调用service层的查看邀请函的方法
        invitationsServiceImpl.getInvitationResponse(r,requestURI);
        //响应数据
        resp.getWriter().println(mapper.writeValueAsString(r));

//        super.doGet(req, resp);
    }
}
